package importExcel

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/spf13/cast"
	"github.com/tealeg/xlsx"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/common/utils"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"io"
	"net/http"
	"os"
	"path"
)

type ImportentErpriseCustomerExcelApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewImportentErpriseCustomerExcelApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ImportentErpriseCustomerExcelApiLogic {
	hostname, _ := os.Hostname()
	return &ImportentErpriseCustomerExcelApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ImportentErpriseCustomerExcelApiLogic) ImportentErpriseCustomerExcelApi() (resp string, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	file, handler, err := l.Request.FormFile("file")
	if err != nil {
		return "", err
	}
	defer file.Close()
	fileType := path.Ext(handler.Filename)
	if !k.IsContains([]string{".xlsx", ".xls"}, fileType) {
		return "", errors.New("只能是.xlsx,.xls其中一种格式")
	}
	workDir, _ := os.Getwd()
	dst := path.Join(workDir, handler.Filename)
	f, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println("本地创建失败")
		return "", errors.New("上传文件失败")
	}
	defer f.Close()
	io.Copy(f, file)
	// 读取Excel文件内容
	xlFile, err := xlsx.OpenFile(dst)
	if err != nil {
		fmt.Println("读取excel失败", err)
		return "", errors.New("上传失败")
	}
	fmt.Println(accountInfo)
	// 单独设置超时时间
	//ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	//defer cancel()
	for _, sheet := range xlFile.Sheets {
		fmt.Println("开始读取数据")
		for index, row := range sheet.Rows { // 循环行
			if index > 2 {
				for _, cell := range row.Cells { // 循环每列
					// 获取单元格的值并输出
					fmt.Printf("%s\t", cell.String())
				}
				fmt.Println()
				if len(row.Cells) == 0 {
					break
				}
				companyName := row.Cells[0].String()
				name := row.Cells[1].String()
				mobile := row.Cells[2].String()
				status := row.Cells[3].String()
				types := row.Cells[4].String()
				address1 := row.Cells[5].String()
				address2 := row.Cells[6].String()
				logx.WithContext(l.ctx).Infof("当前行数据:(公司名称:%v,负责人:%v,手机号码:%v,客户状态:%v,客户类型:%v,省市县镇地址:%v,地址:%v)", companyName, name, mobile, status, types, address1, address2)
				_, err = service.EnterpriseCustomerService.GetByNameApi(l.ctx, accountInfo.EnterpriseId, companyName)
				if !errors.Is(err, gorm.ErrRecordNotFound) {
					continue
				}
				var proviceCode = ""
				var cityCode = ""
				var countyCode = ""
				var townCode = ""
				if address1 != "" {
					addressList := utils.AddressSplit(address1)
					if k.IsContains([]int{3, 4}, len(addressList)) {
						proviceCode, _ = service.AreaService.GetAreaCodeApi(l.ctx, addressList[0])
						cityCode, _ = service.AreaService.GetAreaCodeApi(l.ctx, addressList[1])
						countyCode, _ = service.AreaService.GetAreaCodeApi(l.ctx, addressList[2])
						if len(addressList) == 4 {
							townCode, _ = service.AreaService.GetAreaCodeApi(l.ctx, addressList[3])
						}
					}
				}
				if err = service.EnterpriseCustomerService.Create2Api(l.ctx, &model.EnterpriseCustomerEntity{
					EnterpriseID: accountInfo.EnterpriseId, // 关联到enterprise表主键id
					Name:         companyName,              // 门店名称
					Person:       name,                     // 负责人
					Mobile:       mobile,                   // 联系电话
					Logo:         "",                       // 状态logo
					Status:       cast.ToInt64(status),     // 状态0：营业  1：停业
					Types:        cast.ToInt64(types),      // 客户类型0：公司，1：门店，2：个人
					ProvinceCode: proviceCode,              // 省份code
					CityCode:     cityCode,                 // 城市code
					CountyCode:   countyCode,               // 县、区code
					TownCode:     townCode,                 // 乡镇code
					Address:      address2,                 // 具体地址
					FullAddress:  address1 + address2,      // 拼接省市县地址
				}); err != nil {
					continue
				}
			}
		}
	}
	if err = os.Remove(dst); err != nil {
		fmt.Println("删除文件失败", err)
	}
	fmt.Println(dst, "?")
	return "上传成功", nil
}
